package com.zking.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.net.URLDecoder;
import java.util.Properties;

/**
 * 获取druid数据源
 */
public class DBPoolUtils {

    //数据源
    private static DataSource ds;

    static {
        try {
            //获取DBPoolUtils.class文件所在的跟目录，com的上一级
            String path = DBPoolUtils.class.getResource("/").getPath();
            //使用Java代码把中文编码
            //URLEncoder.encode("你Java", "UTF-8");
            //将路径中的url编码进行解码[编码中文和某些特殊符号(+)]
            path = URLDecoder.decode(path, "UTF-8") + "com/zking/config/db.properties";
            //创建一个Properties加载文件
            Properties p = new Properties();
            //加载文件
            p.load(new FileInputStream(path));
            //创建了一个具有连接池属性的druid数据源
            ds = DruidDataSourceFactory.createDataSource(p);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Properties getProperties(String fileName) {
        Properties p = new Properties();
        //加载文件的路径
        //动态的获取文件的路径
        String path = DBPoolUtils.class.getResource("/").getPath();
        try {
            //decode:将url编码进行解码
            path = URLDecoder.decode(path, "UTF-8") + fileName;
            //加载这个路径
            p.load(new FileInputStream(path));
            //System.out.println(path);
            return p;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static DataSource getDataSource() {
        return ds;
    }



    public static void main(String[] args) throws Exception {

    }


}
